import { Form, Drawer, Row, Col, Input, InputNumber, Space, Button, Divider, Select, DatePicker } from 'antd';
import { useEffect, useState } from 'react';
import { connect } from 'umi';
import { normFile, uuid } from '@/utils/upload';
import AliyunOSSUpload from '@/components/AliyunOSSUpload/App';
import locale from 'antd/es/date-picker/locale/zh_CN';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;

const DataForm = (props) => {
  const { dispatch, submitting, mchList } = props;
  const { dataForm, setDataForm, tablePayload, setTablePayload } = props.data;
  const [form] = Form.useForm();
  const [cover, setCover] = useState([]);
  const [validType, setValidType] = useState(0);

  /* 初始化表单数据 */
  useEffect(() => {
    if (!dataForm || !dataForm.data) {
      form.setFieldsValue({ validType: 0, limitNum: 0, status: 1, orderby: 0 });
    }

    if (dataForm && dataForm.data) {
      let cover_ = [];
      if (dataForm.data.cover) {
        cover_ = [{
          uuid: uuid(),
          name: dataForm.data.cover.split('/').pop(),
          status: 'done',
          url: dataForm.data.cover,
        }];
      }
      setCover(cover_);

      form.setFieldsValue({
        ...dataForm.data,
        issueMchIds: dataForm.data.issueMchIds ? dataForm.data.issueMchIds : undefined,
        mchIds: dataForm.data.mchIds ? dataForm.data.mchIds : undefined,
        time: dataForm.data.startTime ? [dayjs(dataForm.data.startTime, 'YYYY-MM-DD'), dayjs(dataForm.data.endTime, 'YYYY-MM-DD')] : [],
        cover: cover_,
      });

      setValidType(dataForm.data.validType);
    }
  }, [dataForm, form]);

  /* 确定操作 */
  function onOk() {
    form.validateFields().then(values => {
      if (submitting) {
        return;
      }
      let keys = Object.keys(values);
      keys.forEach(d => {
        values[d] = values[d] === null ? undefined : values[d];
      });

      if (values.cover && (values.cover.length > 0)) {
        values.cover = values.cover.filter(d => d.status === 'done').pop().url;
      } else {
        values.cover = '';
      }

      if (values.time) {
        values.startTime = dayjs(values.time[0]).format('YYYY-MM-DD') + ' 00:00:00';
        values.endTime = dayjs(values.time[1]).format('YYYY-MM-DD') + ' 23:59:59';
      }

      dispatch({
        type: values.id ? 'POperationCoupon/edit' : 'POperationCoupon/add',
        payload: values,
        callback: () => {
          onCancel();
          setTablePayload({ ...tablePayload });
        },
      });
    });
  }

  /* 取消操作 */
  function onCancel() {
    setDataForm(undefined);
    form.resetFields();
    setCover([]);
    setValidType(0);
  }

  return (
    <Drawer
      title={dataForm ? dataForm.title : ''}
      open={dataForm ? dataForm.visible : false}
      onClose={onCancel}
      forceRender={true}
      width={940}
      headerStyle={{ padding: '8px 24px' }}
      bodyStyle={{ paddingBottom: 80 }}
      extra={
        <Space>
          <Button onClick={onCancel}>取消</Button>
          <Button loading={submitting} onClick={onOk} type="primary">提交</Button>
        </Space>
      }
    >
      <Form layout="horizontal" labelCol={{ span: 6 }} form={form}>
        {dataForm && dataForm.data && (
          <Form.Item name="id" hidden={true}>
            <Input />
          </Form.Item>
        )}
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="mchIds" label="可用商家"
              rules={[
                { required: true, message: '可用商家不能为空' },
              ]}>
              <Select
                placeholder="请选择可用商家" options={mchList.map(d => {
                d.value = d.id;
                return d;
              })}
                allowClear showSearch mode={'multiple'} maxTagCount={1}
                filterOption={(input, option) => (option?.label ?? '').includes(input)}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="issueMchIds" label="发券商家"
              rules={[
                { required: false, message: '发券商家不能为空' },
              ]}>
              <Select
                placeholder="请选择发券商家" options={mchList.map(d => {
                d.value = d.id;
                return d;
              })}
                allowClear showSearch mode={'multiple'} maxTagCount={1}
                filterOption={(input, option) => (option?.label ?? '').includes(input)}
              />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="type" label="卡券类型"
              rules={[
                { required: true, message: '卡券类型不能为空' },
              ]}
            >
              <Select placeholder="请选择卡券类型">
                <Select.Option value={0}>兑换券</Select.Option>
                <Select.Option value={1}>现金券</Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="name" label="卡券名称"
              rules={[
                { required: true, message: '卡券名称不能为空' },
              ]}>
              <Input placeholder="请输入卡券名称" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="receiveType" label="领取方式"
              rules={[
                { required: true, message: '领取方式不能为空' },
              ]}
            >
              <Select placeholder="请选择领取方式">
                <Select.Option value={0}>后台发放</Select.Option>
                <Select.Option value={1}>用户领取</Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="limitNum" label="限领次数"
              tooltip={'领取方式‘用户领取’时有效，为‘0’时不限制'}
              rules={[
                { required: true, message: '限领次数不能为空' },
              ]}>
              <InputNumber style={{ width: '100%' }} placeholder="请输入限领次数" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="validType" label="有效期类型"
              rules={[
                { required: true, message: '有效期类型不能为空' },
              ]}
            >
              <Select placeholder="请选择有效期类型" onSelect={e => setValidType(e)}>
                <Select.Option value={0}>指定日期范围</Select.Option>
                <Select.Option value={1}>领取后N天有效</Select.Option>
              </Select>
            </Form.Item>
          </Col>
          {(validType === 0) && (
            <>
              <Col span={12}>
                <Form.Item
                  name="time" label="有效期间"
                  rules={[
                    { required: true, message: '有效期间不能为空' },
                  ]}>
                  <RangePicker locale={locale} style={{ width: '100%' }} format={'YYYY-MM-DD'} />
                </Form.Item>
              </Col>
            </>
          )}
          {(validType === 1) && (
            <>
              <Col span={12}>
                <Form.Item
                  name="dayNum" label="有效期天"
                  rules={[
                    { required: true, message: '有效期天不能为空' },
                  ]}>
                  <InputNumber style={{ width: '100%' }} placeholder="请输入有效期天" />
                </Form.Item>
              </Col>
            </>
          )}
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="rawAmount" label="卡券价值"
              rules={[
                { required: true, message: '卡券价值不能为空' },
              ]}>
              <InputNumber min={0} step={0.01} style={{ width: '100%' }} placeholder="请输入卡券价值" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="quantity" label="卡券数量"
              rules={[
                { required: true, message: '卡券数量不能为空' },
              ]}>
              <InputNumber style={{ width: '100%' }} placeholder="请输入卡券数量" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="status" label="当前状态"
              rules={[
                { required: true, message: '当前状态不能为空' },
              ]}
            >
              <Select placeholder="请选择当前状态">
                <Select.Option value={1}>正常</Select.Option>
                <Select.Option value={0}>停用</Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="orderby" label="排序属性"
              rules={[
                { required: true, message: '排序属性不能为空' },
              ]}>
              <InputNumber style={{ width: '100%' }} placeholder="请输入排序属性" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="description" label="卡券说明"
              rules={[
                { required: true, message: '卡券说明不能为空' },
              ]}>
              <Input.TextArea rows={5} placeholder="请输入卡券说明" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="remark" label="备注信息"
              rules={[
                { required: false, message: '备注信息不能为空' },
              ]}
            >
              <Input.TextArea rows={5} placeholder="请输入备注信息" />
            </Form.Item>
          </Col>
        </Row>
        <Divider style={{ marginTop: 0 }} />
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              labelCol={{ span: 3 }}
              name={'cover'}
              label="封面图"
              tooltip="宽高800*800px，大小5M内"
              rules={[
                { required: false, message: '封面图不能为空' },
              ]}
              valuePropName="fileList" getValueFromEvent={normFile}>
              <AliyunOSSUpload
                data={{ images: cover, setImages: setCover, size: 5, len: 1, accept: 'image/*' }} />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Drawer>
  );
};


export default connect(({ loading, MchCommon }) => {
  return {
    submitting: loading.effects['POperationCoupon/add'] || loading.effects['POperationCoupon/edit'],
    mchList: MchCommon.mchList,
  };
})(DataForm);

